package job

import (
	"context"
	"gitee.com/crack007/goose"
	"gitee.com/crack007/goose/schedule"
	"github.com/crack007/go-im/pb"
	"github.com/crack007/go-im/src/common/model"
)

type SentinelPingJob struct {
	schedule.DefaultJob
	client          pb.SentinelServiceClient
	targetSentinel  *model.SentinelModel
	sourceSentinel  *model.SentinelModel
	timeoutCallback func(targetSentinel *model.SentinelModel)
}

func NewSentinelPingJob(client pb.SentinelServiceClient, targetSentinel *model.SentinelModel, sourceSentinel *model.SentinelModel, timeoutCallback func(targetSentinel *model.SentinelModel)) *SentinelPingJob {
	return &SentinelPingJob{
		DefaultJob: schedule.DefaultJob{
			JobDelay: 5000,
		},
		client:          client,
		targetSentinel:  targetSentinel,
		sourceSentinel:  sourceSentinel,
		timeoutCallback: timeoutCallback,
	}
}

func (d *SentinelPingJob) Run(task *schedule.Task) {
	// TODO 监控节点下线或异常处理
	resp, err := d.client.Ping(context.Background(), &pb.PingReq{SourceId: d.sourceSentinel.Id})
	if err != nil {
		d.Cancel()
		d.timeoutCallback(d.targetSentinel)
		return
	}
	// 记录最后检测时间
	d.targetSentinel.RefreshLastConnected()
	goose.GetLogger().Trace("node pong->id:%s", resp.SourceId)
}

func (d *SentinelPingJob) IsCron() bool {
	return true
}
